package org.jivesoftware.spark.crowd.packet;

import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.provider.PacketExtensionProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.spark.crowd.Param;
import org.xmlpull.v1.XmlPullParser;

public class MParser implements PacketExtension{
	private String en;
	private String xmlns;
	private String crowdName;
	private String memberJID;
	@Override
	public String getElementName() {
		// TODO Auto-generated method stub
		return en;
	}

	@Override
	public String getNamespace() {
		// TODO Auto-generated method stub
		return xmlns;
	}
	
	public void setEn(String en) {
		this.en = en;
	}

	public void setXmlns(String xmlns) {
		this.xmlns = xmlns;
	}

	@Override
	public String toXML() {
		StringBuilder sb = new StringBuilder();
		sb.append("<")
		.append(Param.CROWD_SERVICE_NAME)
		.append(" xmlns=\"")
		.append(xmlns)
		.append("\"")
		.append(" crowdname=\"")
		.append(crowdName)
		.append("\"")
		.append(" memberjid=\"")
		.append(memberJID)
		.append("\"/>");

		return sb.toString();
	}
	
	
	public String getCrowdName() {
		return crowdName;
	}

	public void setCrowdName(String crowdName) {
		this.crowdName = crowdName;
	}

	public String getMemberJID() {
		return memberJID;
	}

	public void setMemberJID(String memberJID) {
		this.memberJID = memberJID;
	}


	public static class MParserProvider implements PacketExtensionProvider{
		private static Object LOCK = new Object();
		private static MParserProvider instance;
		public static MParserProvider getInstance(){
			synchronized(LOCK){
			if(instance == null)
				instance = new MParserProvider();
			}
			return instance;
		}
		private MParserProvider(){
			ProviderManager.getInstance().addExtensionProvider(Param.CROWD_SERVICE_NAME, Param.message_NS, this);
		}
		@Override
		public PacketExtension parseExtension(XmlPullParser parser)
				throws Exception {
			MParser mParser = new MParser();
			String en = parser.getName();
			String xmlns = parser.getNamespace();
			String crowdName = parser.getAttributeValue("", "crowdname");
			String memberJID = parser.getAttributeValue("", "memberjid");
			
			mParser.setCrowdName(crowdName);
			mParser.setMemberJID(memberJID);
			mParser.setEn(en);
			mParser.setXmlns(xmlns);
			
			return mParser;
		}
		
	}

}
